package com.wzh.store.controller;

import com.wzh.store.entity.Address;
import com.wzh.store.service.IAddressService;
import com.wzh.store.service.IDistrictService;
import com.wzh.store.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author wzh
 * @create 2022/4/22 19:15
 * @Description：
 */
@RestController
@RequestMapping("addresses")
public class AddressController extends BaseController{
    @Autowired
    public IAddressService iAddressService;
    @Autowired
    public IDistrictService iDistrictService;
    @RequestMapping("add_new_address")
    public JsonResult<Void> addNewAddress(HttpSession session, Address address){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        String provinceCode = address.getProvinceCode();
        String  cityCode= address.getCityCode();
        String areaCode = address.getAreaCode();
        String province = iDistrictService.getNameByCode(provinceCode);
        String ciyt = iDistrictService.getNameByCode(cityCode);
        String area = iDistrictService.getNameByCode(areaCode);
        address.setCityName(ciyt);
        address.setProvinceName(province);
        address.setAreaName(area);
        iAddressService.addNewAddress(uid,username,address);
        return new JsonResult<>(ok,"新增收货地址成功");

    }


    @RequestMapping({"/",""})
    public JsonResult<List<Address>> getByUid(HttpSession session){
        Integer uid = getUidFromSession(session);
        List<Address> list = iAddressService.getByUid(uid);
        return new JsonResult<>(ok,list);
    }

    @RequestMapping("{aid}/set_default")
    public JsonResult<Void> setDefault(@PathVariable("aid") Integer aid,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        iAddressService.setDefault(aid,uid,username);
        return new JsonResult<>(ok,"修改默认地址成功");
    }
    @RequestMapping("/{aid}/delete")
    public JsonResult<Void> delete(@PathVariable("aid") Integer aid,HttpSession session){
        String username = getUsernameFromSession(session);
        Integer uid = getUidFromSession(session);
        iAddressService.delete(aid,uid,username);
        return new JsonResult<>(ok,"删除成功");
    }

}
